use mongodb::{Collection, Database};

pub mod data;
pub mod role;
pub mod user;
pub mod util;

#[derive(Clone)]
pub struct State {
    pub db: Database,
}

/// Create a `tide::Server` for data storage service.
pub fn data(database: Database) -> tide::Server<State> {
    let mut app = tide::with_state(State { db: database });
    app.at("/:collection").get(data::find_objects).post(data::insert_object);
    app.at("/:collection/:id")
        .get(data::find_object)
        .put(data::update_object)
        .patch(data::modify_object)
        .delete(data::delete_object);
    app
}

#[derive(Clone)]
pub struct UserState {
    pub users: Collection,
    pub token_generator: user::TokenGenerator,
}

/// Create a `tide::Server` for user account service.
pub fn user(users: Collection, token_generator: user::TokenGenerator) -> tide::Server<UserState> {
    let mut app = tide::with_state(UserState { users, token_generator });
    app.at("/register").post(user::register);
    app.at("/login").post(user::login);
    app.at("/list").get(user::list);
    app.at("/info/:id").get(user::info);
    app.at("/update/:id").put(user::update);
    app.at("/change_password/:id").put(user::change_password);
    app.at("/switch_role").post(user::switch_role);
    app
}
